'use strict';

const Controller = require('egg').Controller;
const Error = require('../../class/error');
class BannerController extends Controller {
  /**
   * @description 首页轮播图部分
   * @author xiezuobing[948466]<435321508@qq.com>
   * @memberof HomeController
   */
  async list() {
    const ctx = this.ctx;
    ctx.locals = {
      banners: await this.service.banner.all()
    }
    // ctx.body = ctx.locals;
    await ctx.render('admin/banner/list.html');
  }

  /**
   * @description 新增与编辑
   * @author xiezuobing[948466]<435321508@qq.com>
   * @memberof BannerController
   */
  async addOrEditJson() {
    const ctx = this.ctx;
    let values = {
      href: ctx.query.href,
      name: ctx.query.name,
      img: ctx.query.img,
      create_time: new Date(),
      modify_time: new Date()
    }
    try{
      if(ctx.query.id) {
        values.id = ctx.query.id;
        await this.service.banner.update(values)
      } else {
        await this.service.banner.create(values)
      }
      ctx.body = Error.SUCCESS;
    }catch(e) {
      ctx.body = Error.UNKOWN;
    }
  }

  async addJson() {
    const ctx = this.ctx;
    try {
      let values = {
        href: ctx.query.href,
        name: ctx.query.name,
        img: ctx.query.img,
        create_time: new Date(),
        modify_time: new Date()
      }
      await this.service.banner.create(values)
      ctx.body = Error.SUCCESS;
    } catch (e) {
      ctx.body = Error.UNKOWN;
    }
  }

  /**
   * @description 编辑
   * @author xiezuobing[948466]<435321508@qq.com>
   * @memberof BannerController
   */
  async editJson() {
    const ctx = this.ctx;
    try {
      if(!ctx.query.id) {
        ctx.body = Error.LESSPRIMARYKEY;
        return;
      }
      let values = ctx.query;
      values.modify_time = new Date(),
      await this.service.banner.update(values)
      ctx.body = Error.SUCCESS;
    } catch (e) {
      ctx.body = Error.UNKOWN;
    }
  }

  /**
   * @description 物理删除
   * @author xiezuobing[948466]<435321508@qq.com>
   * @memberof BannerController
   */
  async deleteJson() {
    const ctx = this.ctx;
    try {
      if(!ctx.query.bannerId) {
        ctx.body = Error.LESSPRIMARYKEY;
        return;
      }
      await this.service.banner.delete(ctx.query.bannerId);
      ctx.body = Error.SUCCESS;
    } catch (e) {
      ctx.body = Error.UNKOWN;
    }
  }

}

module.exports = BannerController;